//
//  ZYHttpInterceptor.swift
//  ZYHttp
//
//  Created by Yi Zhou on 2025/1/14.
//

import Foundation
import Alamofire

//MARK: - 拦截器
final class ZYHttpInterceptor: RequestInterceptor, Sendable {
    
    // 请求前的拦截处理
    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        var adaptedRequest = urlRequest
        // 添加公共头部信息
        adaptedRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        completion(.success(adaptedRequest))
    }
    
    // 响应后的拦截处理
    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
        if let response = request.task?.response as? HTTPURLResponse,
           response.statusCode == 401 { // 认证失败时尝试刷新令牌
            // 在这里实现刷新令牌的逻辑
            debugPrint("request response：\(response)")
            
            // 刷新成功后重新尝试请求
            completion(.retry)
        } else {
            debugPrint("")
        }
    }
}
